import Flutter
import UIKit

public class SwiftGkbSignalrPlugin: NSObject, FlutterPlugin {

    lazy private var coordinator: SignalRCoordinator = {
        SignalRCoordinator.instance
    }()
    private var _channel : FlutterMethodChannel?
    
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "gkb_signalr", binaryMessenger: registrar.messenger())
    let instance = SwiftGkbSignalrPlugin()
    instance._channel = channel;
    registrar.addMethodCallDelegate(instance, channel: channel)
      
    SignalRCoordinator.instance.delegate = instance;
  }
    //---------------------------------------------------------------------------------------------
    // FlutterMethodChannel Interface Methods
    // --------------------------------------------------------------------------------------------
  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
      switch call.method {
      case "connectToServer":
          coordinator.connectToServer(call.arguments)
          result(nil)
      case "ackMessage":
          coordinator.ackMessage(call.arguments)
          result(nil)
      case "stop":
          coordinator.stop()
          result(nil)
      case "reconnect":
          coordinator.reconnect()
          result(nil)
      default:
          result(FlutterMethodNotImplemented)
      }
  }
}


extension SwiftGkbSignalrPlugin : SignalRCoordinatorDelegate{
    func onConnectStateChanged(_ state: Bool) {
        _channel?.invokeMethod("ConnectionStatus", arguments: state)
    }
    
    func onMessageReceived(_ message: String) {
        _channel?.invokeMethod("ReceiveMessage", arguments: message)
    }
}
